//
//  LLLabelListVM.m
//  LLLabel
//
//  Created by LQ on 2020/12/9.
//

#import "WKLabelListVM.h"
#import "WKLabelListCell.h"
#import "WKLabelAddCell.h"
#import "WKLabelAddVC.h"

@interface WKLabelListVM ()



@end

@implementation WKLabelListVM

- (NSArray<NSDictionary *> *)tableSectionMaps {
    if(!self.labels) {
        return nil;
    }
    NSMutableArray *items = [NSMutableArray array];
    [items addObject:@{
        @"class": WKLabelAddModel.class,
        @"onClick":^{
            WKLabelAddVC *vc = [[WKLabelAddVC alloc] init];
            [[WKNavigationManager shared] pushViewController:vc animated:YES];
        }
    }];
    for (WKLabelResp *label in self.labels) {
        NSMutableArray *names = [NSMutableArray array];
        if(label.members && label.members.count>0) {
            for (NSString *uid in label.members) {
               WKChannelInfo *channelInfo = [[WKSDK shared].channelManager getChannelInfo:[WKChannel personWithChannelID:uid]];
                [names addObject:channelInfo?channelInfo.displayName:@""];
            }
        }
        [items addObject:@{
            @"class": WKLabelListModel.class,
            @"title": label.name?:@"",
            @"num":@(label.count),
            @"desc": [names componentsJoinedByString:@"、"],
            @"onClick":^{
                WKLabelAddVC *vc = [[WKLabelAddVC alloc] init];
                vc.label = label;
                [[WKNavigationManager shared] pushViewController:vc animated:YES];
            }
        }];
    }
    return @[
        @{
            @"height": @(0.01f),
            @"items": items,
        }
    ];
}

- (AnyPromise *)requestDeleteLabel:(NSString *)_id {
   return [[WKAPIClient sharedClient] DELETE:[NSString stringWithFormat:@"label/%@",_id] parameters:nil];
}

- (void)requestData:(void (^)(NSError * _Nullable))complete {
    __weak typeof(self) weakSelf = self;
    [[WKAPIClient sharedClient] GET:@"label" parameters:nil model:WKLabelResp.class].then(^(NSArray<WKLabelResp*>*resps){
        weakSelf.labels = [NSMutableArray arrayWithArray:resps];
        complete(nil);
    }).catch(^(NSError *err){
        complete(err);
    });
}

@end

@implementation WKLabelResp

+ (WKModel *)fromMap:(NSDictionary *)dictory type:(ModelMapType)type {
    WKLabelResp *resp = [WKLabelResp new];
    resp._id = dictory[@"id"];
    resp.name = dictory[@"name"]?:@"";
    resp.count = [dictory[@"count"] integerValue];
    
    NSArray<NSDictionary*> *members = dictory[@"members"];
    if(members && members.count>0) {
        NSMutableArray *memberUIDs = [NSMutableArray array];
        for (NSDictionary *memberDict in members) {
            [memberUIDs addObject:memberDict[@"uid"]];
        }
        resp.members = memberUIDs;
    }
    return resp;
}

@end
